<template>
    <div>
      <div class="gva-search-box">
        <el-form ref="searchForm" :inline="true" :model="searchInfo">
          <el-form-item label="">
            <el-input v-model="searchInfo.dataName" placeholder="请输入数据名称" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
            <el-button icon="refresh" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="gva-table-box">
        <div class="gva-btn-list">
          <el-button type="primary" icon="plus" @click="addService">新增</el-button>
          <!-- <el-button type="primary" icon="plus" @click="addService">修改</el-button>
          <el-button type="primary" icon="plus" @click="addService">删除</el-button> -->
        </div>

        <el-table :data="sortedData" row-key="ServiceId" @sort-change="sortChange">
          <el-table-column align="left" label="序号" min-width="100" v-slot="scope">
            {{ (page - 1) * pageSize + scope.$index + 1 }}
          </el-table-column>
          <el-table-column align="left" label="数据名称" min-width="150" prop="DataName" sortable />
<!--          <el-table-column align="left" label="数据Id" min-width="150" prop="DataID" />-->
          <el-table-column align="left" label="共享次数" min-width="200" prop="ShareTimes" sortable />
          <el-table-column align="left" label="数据类型" min-width="200" prop="DataType" sortable >
            <template #default="scope">
            <span>{{ formatType(scope.row.DataType) }}</span>
          </template>
          </el-table-column>
          <el-table-column align="left" label="是否共享" min-width="200" prop="IsOpen" sortable >
            <template #default="scope">
            <span>{{ formatStatus(scope.row.IsOpen) }}</span>
          </template>
          </el-table-column>
          <el-table-column align="left" label="数据大小" min-width="200" prop="DataSize" sortable />

          <el-table-column align="left" fixed="right" label="操作" width="400">
            <template #default="scope">
              <el-button icon="edit" type="primary" link @click="openDetailDialog(scope.row)">详情</el-button>
              <el-button icon="edit" type="primary" link @click="openUpdateDialog(scope.row)">修改</el-button>
              <el-button icon="delete" type="primary" link @click="deleteService(scope.row)">删除</el-button>
              <el-button icon="download" type="primary" link @click="downLoadData(scope.row)">下载</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="gva-pagination">
          <el-pagination
              :current-page="page"
              :page-size="pageSize"
              :page-sizes="[10, 30, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
          />
        </div>
      </div>
      <el-drawer v-model="detailDialog" size="60%" :show-close="false" :close-on-press-escape="false" :close-on-click-modal="false">
        <template #header>
          <div class="flex justify-between items-center">
            <span class="text-lg">服务详情</span>
            <div>
              <el-button @click="closeDetailDialog">取消</el-button>
<!--               <el-button type="primary" v-show="flagS" @click="submitDetailForm">确定</el-button>
              <el-button type="primary" v-show="flagU" @click="updateDetailForm">保存</el-button> -->
            </div>
          </div>
        </template>
        <el-form ref="detailForm" :rules="rules" :model="serviceInfo" label-width="120px">
          <el-form-item label="数据" prop="dataName">
            <el-input v-model="serviceInfo.DataName" />
          </el-form-item>
          <el-form-item label="数据类型" prop="DataType">
            <el-input v-model="serviceInfo.DataType" />
          </el-form-item>
          <el-form-item label="节点" prop="NodeID">
            <el-input v-model="serviceInfo.NodeID" />
          </el-form-item>
          <el-form-item label="评估价格" prop="EvaluateValue">
            <el-input v-model="serviceInfo.EvaluateValue" />
          </el-form-item>
          <el-form-item label="评估时间" prop="EvaluateTime">
            <el-input v-model="serviceInfo.EvaluateTime" />
          </el-form-item>
          <el-form-item label="存储时间" prop="SaveTime">
            <el-input v-model="serviceInfo.SaveTime" >
            </el-input>
          </el-form-item>
          <el-form-item label="数据介绍" prop="Introduction">
            <el-input v-model="serviceInfo.Introduction" >

            </el-input>
          </el-form-item>

          <el-form-item label="是否共享" prop="IsOpen">
            <el-radio-group v-model="serviceInfo.IsOpen">
                <el-radio label= "1" >是</el-radio>
                <el-radio label= "2" >否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审核方式" prop="auditMethod">
            <el-radio-group v-model="serviceInfo.auditMethod">
                <el-radio label="自动">自动</el-radio>
                <el-radio label="人工">人工</el-radio>
            </el-radio-group>
          </el-form-item>

        </el-form>
        <div class="flex justify-between items-center box">
            <span class="text-l">共享记录</span>
            <span class="text-l " >共享次数: {{ serviceInfo.ShareTimes }}</span>
        </div>

        <el-table :data="serviceInfo.shareArray" row-key="sharePerson" class="box">
          <el-table-column align="left" label="序号" min-width="100" v-slot="scope">
            {{ scope.$index + 1 }}
          </el-table-column>
          <el-table-column align="left" label="分享用户" min-width="150" prop="sharePerson" sortable />
          <el-table-column align="left" label="分享时间" min-width="150" prop="shareDate" />
        </el-table>

      </el-drawer>
      <el-drawer v-model="detailDialogS" size="60%" :show-close="false" :close-on-press-escape="false" :close-on-click-modal="false">
        <template #header>
          <div class="flex justify-between items-center">
            <span class="text-lg">服务详情</span>
            <div>
              <el-button @click="closeDetailDialog">取消</el-button>
              <el-button type="primary" v-show="flagS" @click="submitDetailForm">确定</el-button>
              <el-button type="primary" v-show="flagU" @click="updateDetailForm">保存</el-button>
            </div>
          </div>
        </template>
        <el-form ref="detailForm" :rules="rules" :model="fileInfo" label-width="120px">
  <el-form-item label="数据" prop="file">
    <input type="file" @change="handleFileChange" />
  </el-form-item>

  <el-form-item label="数据类型" prop="DataType">
    <el-select v-model="fileInfo.DataType" placeholder="请选择上传类型">
      <el-option label="文档" value="1">文档</el-option>
      <el-option label="图片" value="2">图片</el-option>
      <el-option label="视频" value="3">视频</el-option>
      <el-option label="关系数据" value="4">关系数据</el-option>
    </el-select>
  </el-form-item>

  <el-form-item label="数据是否开放" prop="IsOpen">
    <el-select v-model="fileInfo.IsOpen" placeholder="是否开放">
      <el-option label="开放" value="1">开放</el-option>
      <el-option label="关闭" value="2">关闭</el-option>
    </el-select>
  </el-form-item>

  <el-form-item label="文件说明" prop="Introduction">
  <el-input
    type="textarea"
    v-model="fileInfo.Introduction"
    rows="4"
  />
</el-form-item>
</el-form>
      </el-drawer>



      <el-drawer v-model="detailDialogU" size="60%" :show-close="false" :close-on-press-escape="false" :close-on-click-modal="false">
        <template #header>
          <div class="flex justify-between items-center">
            <span class="text-lg">服务详情</span>
            <div>
              <el-button @click="closeDetailDialog">取消</el-button>

              <el-button type="primary" v-show="flagU" @click="updateDetailForm">保存</el-button>
            </div>
          </div>
        </template>
        <el-form ref="detailForm" :rules="rules" :model="updateInfo" label-width="120px">
  <el-form-item label="数据" prop="file">
    <input type="file" @change="handleFileChangeU" />
  </el-form-item>
  <el-form-item label="数据Id" prop="DataID">
    <el-input v-model="updateInfo.DataID" />
  </el-form-item>
  <el-form-item label="数据类型" prop="DataType">
    <el-select v-model="updateInfo.DataType" placeholder="请选择上传类型">
      <el-option label="1" value="1">文档</el-option>
      <el-option label="2" value="2">图片</el-option>
      <el-option label="3" value="3">视频</el-option>
      <el-option label="4" value="4">关系数据</el-option>
    </el-select>
  </el-form-item>

  <el-form-item label="数据是否开放" prop="IsOpen">
    <el-select v-model="updateInfo.IsOpen" placeholder="是否开放">
      <el-option label="1" value="1">开放</el-option>
      <el-option label="2" value="2">关闭</el-option>
    </el-select>
  </el-form-item>

  <el-form-item label="文件说明" prop="Introduction">
  <el-input
    type="textarea"
    v-model="updateInfo.Introduction"
    rows="4"
  />
</el-form-item>
</el-form>
      </el-drawer>

    </div>
  </template>

  <script setup>
  import { ref, reactive,computed, nextTick } from 'vue'

  import { ElMessage, ElMessageBox } from 'element-plus'
  import { getlistDataInfo ,deleteDataInfo,
    addData,downLoadInfo,updateData,getDataDetail } from '@/api/userInfo'

  const page = ref(1)
  const total = ref(0)
  const pageSize = ref(10)
  const sortInfo = ref({ prop: '', order: '' })
  const searchInfo = reactive({ dataName: '' })
  const flagS=ref(false)
  const flagU=ref(false)
  const originalTableData = ref([])
  const tableData = ref([])

  const filteredData = computed(() => {
    const filterValue = searchInfo.dataName.toLowerCase()
    return (tableData.value || []).filter(item =>
        item.DataName.toLowerCase().includes(filterValue)
    )
  })

  const sortedData = computed(() => {
    const data = [...filteredData.value]
    if (sortInfo.value.prop && sortInfo.value.order) {
      data.sort((a, b) => {
        let aValue = a[sortInfo.value.prop]
        let bValue = b[sortInfo.value.prop]
        if (sortInfo.value.prop === 'UpdatedAt') {
          aValue = new Date(aValue).getTime()
          bValue = new Date(bValue).getTime()
        } else if (sortInfo.value.prop === 'ServiceVersion') {
          aValue = parseInt(aValue)
          bValue = parseInt(bValue)
        }
        if (sortInfo.value.order === 'ascending') {
          return aValue > bValue ? 1 : -1
        } else {
          return aValue < bValue ? 1 : -1
        }
      })
    }
    return data
  })

  const handleSizeChange = (val) => {
    pageSize.value = val
    getTableData()
  }

  const handleCurrentChange = (val) => {
    page.value = val
    getTableData()
  }

  const formatTimestamp=(timestamp)=> {
    const date = new Date(timestamp);

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

  const getTableData = async () => {

    try {
      const response = await getlistDataInfo( page.value,pageSize.value);
      originalTableData.value = response.data.list; // 保存原始数据
      tableData.value = response.data.list; // 初始化表格数据
      total.value = response.data.total;
    } catch (error) {
      console.error('API Error:', error);
      ElMessage.error('获取数据失败');
    }
  }

  getTableData()

  const uploadUrl = '/your-upload-endpoint';  // 替换为你的上传接口

const handleUploadSuccess = (response, file) => {
  console.log('文件上传成功:', response);
};

const handleUploadError = (error, file) => {
  console.error('文件上传失败:', error);
};

const statusOptions = ref([

  { label: '开放', value: 1 },
  {label: '关闭', value: 2}
])

const formatStatus = (status) => {
  const statusOption = statusOptions.value.find(option => option.value === status)
  return statusOption ? statusOption.label : ''
}

const typeOptions = ref([

  { label: '文档', value: 1 },
  {label: '图片', value: 2},
  {label: '视频', value: 2},
  {label: '关系数据', value: 2}
])

const formatType = (type) => {
  const typeOption = typeOptions.value.find(option => option.value === type)
  return typeOption ? typeOption.label : ''
}

  const onSubmit = () => {
    const searchName = searchInfo.dataName.toLowerCase()
    tableData.value = originalTableData.value.filter(item =>
       String(item.DataName).toLowerCase().includes(searchName)
    )
    total.value = tableData.value.length
    console.log('搜索信息', searchInfo)
  }

  const onReset = () => {
    searchInfo.dataName = ''
    tableData.value = [...originalTableData.value]
    total.value = originalTableData.value.length
    page.value = 1 // 重置分页到第1页
    console.log('重置搜索信息', searchInfo)
  }

  const detailDialog = ref(false)
  const detailDialogS = ref(false)
  const detailDialogU = ref(false)
  const serviceInfo = ref({
    DataID:'',
    DataName:'',
    DataType:'',
    IsOpen:'',
    NodeID:'',
    SaveTime:'',
    Introduction:'',
    EvaluateValue:'',
    EvaluateTime:'',
    DataSize:'',
    StartTimes:'',
    ShareTimes:'',
    shareArray: []
  })

  const fileInfo=ref({
    DataType: '',
    IsOpen: '',
    Introduction: '',
    file: null, // 用于存储上传的文件
  });

  const updateInfo=ref({
    DataID:'',
    DataType: '',
    IsOpen: '',
    Introduction: '',
    file: null, // 用于存储上传的文件
  })

  const handleFileChange = (event) => {
  const file = event.target.files[0]; // 获取第一个选中的文件
  if (file) {
    fileInfo.value.file = file; // 存储文件对象
  } else {
    fileInfo.value.file = null; // 清空文件信息
    ElMessage.error('请选择一个有效的文件');
  }
};

const handleFileChangeU = (event) => {
  const file = event.target.files[0]; // 获取第一个选中的文件
  if (file) {
    updateInfo.value.file = file; // 存储文件对象
  } else {
    updateInfo.value.file = null; // 清空文件信息
    ElMessage.error('请选择一个有效的文件');
  }
};



  const rules = ref({
    businessName: [{ required: true, message: '请输入业务名称', trigger: 'blur' }],
    authorization: [{ required: true, message: '请输入授权信息', trigger: 'blur' }],
    application: [{ required: true, message: '请输入许可配置', trigger: 'blur' }],
    updataTime: [{ required: true, message: '请输入更新时间', trigger: 'blur' }],
    status: [{ required: true, message: '请输入状态', trigger: 'blur' }],
  });


  const addService = () => {
    detailDialogS.value = true
    flagS.value=true

  }



  const openDetailDialog = async(row) => {
    try {
      const response = await getDataDetail( row.DataID);
      serviceInfo.value = {...response.data}
      console.log("serviceInfo:",serviceInfo.value)
      serviceInfo.value.IsOpen=String(serviceInfo.value.IsOpen)
      serviceInfo.value.SaveTime=formatTimestamp(serviceInfo.value.SaveTime)
      detailDialog.value = true
      flagU.value=true
    } catch (error) {
      console.error('API Error:', error);
      ElMessage.error('获取数据失败');
    }

  }

  const openUpdateDialog=(row)=>{
    updateInfo.value={...row}
    detailDialogU.value = true
    flagU.value=true
  }

  const closeDetailDialog = () => {
    detailDialog.value = false
    detailDialogS.value = false
    detailDialogU.value = false
    flagS.value=false
    flagU.value=false
  }


  const submitDetailForm = async () => {


    try {
    console.log("添加数据",fileInfo.value);
    await addData(fileInfo.value);

    ElMessage.success('数据上传成功');
    closeDetailDialog();
    await getTableData(); // 刷新表格数据
  } catch (error) {
    console.error('数据上传失败', error);
    ElMessage.error('数据上传失败');
  }
  };

  const updateDetailForm = async () => {
    try {
    console.log("更新数据",updateInfo.value);
    await updateData(updateInfo.value);

    ElMessage.success('数据更新成功');
    closeDetailDialog();
    await getTableData(); // 刷新表格数据
  } catch (error) {
    console.error('数据更新失败', error);
    ElMessage.error('数据更新失败');
  }
  }

  const deleteService = async (row) => {
    ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      // 调用 API 删除服务
      let param = ''; // 使用 let 声明
      console.log('appid is there:', row.DataID);
      param = row.DataID; // 使用模板字符串

      await deleteDataInfo({"DataId":param}); // 调用删除 API

      ElMessage.success('服务删除成功');
      await getTableData(); // 刷新表格数据
    } catch (error) {
      console.error('删除服务失败', error);
      ElMessage.error('删除服务失败');
    }
  }).catch(() => {
    ElMessage.info('取消删除');
  });
  };

  const downLoadData = async (row) => {
    try {
      const param = row.DataID; // 获取 DataID

      // 使用 window.location.origin 构造下载 URL，这样会自动包含端口号（如果有的话）
      const downloadUrl = `${window.location.origin}/api/UserApi/data_manage/downloadData?DataId=${param}`;

      // 直接跳转到下载链接
      window.location.href = downloadUrl;

      ElMessage.success('下载开始');
      await getTableData(); // 刷新表格数据
    } catch (error) {
      console.error('下载失败', error);
      ElMessage.error('下载失败');
    }
  };






  const sortChange = ({prop, order}) => {
    sortInfo.value = {prop, order}
  }

  </script>


  <style scoped>
  .gva-search-box {
    margin-bottom: 20px;
  }

  .gva-btn-list {
    margin-bottom: 20px;
  }

  .gva-table-box {
    margin-top: 20px;
  }

  .gva-pagination {
    margin-top: 20px;
  }

  .box{
    margin-left: 50px;
    margin-right: 200px;
  }

  .text-l{
    font-size: 20px;
  }

  </style>